<template>
  <div class="body" v-loading="loading">
    <div>
      <el-button type="primary" size="small" icon="el-icon-check" @click="doSave" :disabled="header.status === 'audit'">&nbsp;保&nbsp;存&nbsp;</el-button>
      <el-button type="info" size="small" icon="el-icon-back" @click="gotoList">&nbsp;返&nbsp;回&nbsp;</el-button>
    </div>
    <el-form ref="form" :model="header" size="small" label-width="80px" :inline="true" class="header">
      <div class="audit_icon iconfont icon-yishenhe" v-if="header.status === 'audit'"></div>
      <div class="header_row">
        <el-form-item style="width:260px;" label="单号">{{ header.billNo || '-' }}</el-form-item>
<!--        <el-form-item style="width:360px;" prop="batchNo" label="批号" :rules="[{ required: true, trigger:['blur', 'change'], message: '请输入此项内容' } ]">-->
<!--          <el-input size="small" v-model="header.batchNo" clearable :disabled="header.status === 'audit'"></el-input>-->
<!--        </el-form-item>-->

      </div>
      <div class="header_row">
        <el-form-item prop="remark" label="备注">
          <el-input style="width: 400px" size="small" type="text" v-model="header.remark" :disabled="header.status === 'audit'" />
        </el-form-item>

      </div>
      <div class="header_row">
        <el-form-item prop="prdCount" label="总重" :rules="[{ required: true, trigger:['blur', 'change'], message: '请输入此项内容' } ]" class="p3">
          <el-input-number size="small" v-model="header.prdCount" :precision="2" style="width: 150px;" :min="0" :disabled="header.status === 'audit'" />
          <span class="comment">称重差额：{{ ((header.count || 0) - (header.prdCount || 0)).toFixed(2) }}</span>
        </el-form-item>
      </div>
    </el-form>
    <div class="detail_header">
      <div>
        <template v-if="!header.status || header.status === 'save'">
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteDetail">删除选择行</el-button>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addDetail">添加物料信息</el-button>
        </template>
      </div>

    </div>
    <el-table :data="boxList" class="detail" height="calc(100vh - 325px)" @selection-change="selectChange">
      <el-table-column label="#" width="60" align="center" type="selection" v-if="!header.status || header.status === 'save'"></el-table-column>
      <el-table-column label="No." width="60" align="right" type="index"></el-table-column>
      <el-table-column label="物料编号" width="160" prop="boxNo">
        <template #default="scope">
          <el-select filterable remote :remote-method="e => getMaterialList(e)"  @change="setMaterialValue" v-model="scope.row.materialNo" :disabled="header.status === 'audit'" size="small" clearable class="material" placeholder="请输入物料编码或者名称">
            <el-option v-for="item in this.materialList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName + ' ' + item.fSpecification" :value="item.fNumber" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="物料名称" width="160" prop="boxNo" v-if="header.status === 'audit'">
        <template #default="scope">
          <el-input type="text" size="small" v-model="scope.row.materialName" :disabled="header.status === 'audit'"/>
        </template>
      </el-table-column>
      <el-table-column label="物料规格" width="160" prop="boxNo"  v-if="header.status === 'audit'">
        <template #default="scope">
          <el-input type="text" size="small" v-model="scope.row.materialSpec" :disabled="header.status === 'audit'"/>
        </template>
      </el-table-column>
      <el-table-column label="批次" width="160" align="remark">
        <template #default="scope">
          <el-input type="text" size="small" v-model="scope.row.batchNo" :disabled="header.status === 'audit'"/>
        </template>
      </el-table-column>
      <el-table-column label="重量" width="170" align="center">
        <template #default="scope">
          <el-input-number :id="`w_row_${ scope.$index }`" ref="w_row" size="small" v-model="scope.row.count" :precision="2" style="width: 150px;" :min="0" @keyup.enter="addDetailOnRow($event, scope)" @change="changeDetailCount" :disabled="header.status === 'audit'" />
        </template>
      </el-table-column>
      <el-table-column label="备注" width="250" align="remark">
        <template #default="scope">
          <el-input type="text" size="small" v-model="scope.row.comment" :disabled="header.status === 'audit'"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="90" fixed="right" v-if="!header.status || header.status === 'save'">
        <template #default="scope">
          <el-button type="text" style="color: var(--el-color-danger)" icon="el-icon-delete" @click="deleteRow(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getBoxNo } from '../../utils'
import BatchAddRowDialog from "../components/batchAddRowDialog.vue";
import th from "element-plus/packages/locale/lang/th";

export default {
  components: {BatchAddRowDialog},
  data() {
    return {
      loading: false,
      materialLoading: false,
      materialList: [],
      header: {},
      boxList: [],
      billNoList: [],
      selection: []
    }
  },
  async mounted() {
    let billNo = this.$route.query.billNo
    if (billNo) {
      return this.getBill(billNo)
    }
  },
  methods: {

    batchAddDetail(boxList) {
      this.boxList = this.boxList.concat(boxList)
      this.changeDetailCount()
    },

    gotoList() {
      return this.$router.push('/other/otherOutApplyList')
    },
    async getBill(billNo) {

      this.loading = true
      try {
        let res = await this.callApi('get_other_out_bill_apply_detail', { billNo })
        if (res.res) {
          this.materialList = res.boxList
          this.header = res.header || {}
          this.boxList = res.boxList || []
          this.changeDetailCount()
        }
      } finally {
        this.loading = false
      }
    },

    async doSave() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }
        if (this.boxList.length === 0) {
          this.$message.error('没有分录!')
          return
        }
        for(let i = 0; i < this.boxList.length; i++) {
          if (!this.boxList[i].count) {
            this.$message.error('分录行没有重量!')
            return
          }
        }
        this.loading = true
        let boxList = []
        for(let i = 0; i < this.boxList.length; i++) {
          boxList.push({ materialNo: this.boxList[i].materialNo, count: this.boxList[i].count, comment: this.boxList[i].comment,batchNo: this.boxList[i].batchNo })
        }
        let param = {
          count: this.header.prdCount,
          remark: this.header.remark,
          boxList
        }
        try {
          let res = await this.callApi('save_other_out_Apply', param)
          if (!res.res) {
            return
          }
          var billNo = res.billNo
          // this.header.billNo = res.billNo
          // this.header.status = res.status
          this.$message.success('保存完成!')
          this.getBill(billNo)

        } finally {
          this.loading = false
        }
      })
    },
    async getMaterialList(val) {
      if (!val) {
        this.materialList = []
        return
      }
      this.materialLoading = true
      try {
        const res = await this.callApi('get_material_by_key', { key: val, pageSize: 20 })
        if (!res.res) return
        this.materialList = res.data
      } finally {
        this.materialLoading = false
      }
    },


    selectChange(data) {
      this.selection = data
    },
    async deleteDetail() {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.selection.forEach(sel => {
        for(let i = 0; i < this.boxList.length; i++) {
          if (this.boxList[i].boxNo === sel.boxNo) {
            this.boxList.splice(i, 1)
            break
          }
        }
      })
      this.changeDetailCount()
    },
    addDetail() {
      this.boxList.push({
        count: 0,
        boxNo: '',
        perInBillNo: ''
      })
    },
    addDetailOnRow(e, scope) {
      if (scope.$index === this.boxList.length - 1) {
        if (e.keyCode === 13) {
          this.addDetail()
          this.$nextTick(() => {
            document.querySelector('#w_row_' + ( scope.$index + 1 ) + ' input').focus()
            document.querySelector('#w_row_' + ( scope.$index + 1 ) + ' input').select()
          })
        }
      }
    },
    async deleteRow(idx) {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.boxList.splice(idx, 1)
      this.changeDetailCount()
    },
    changeDetailCount() {
      let total = 0
      for(let i = 0; i < this.boxList.length; i++) {
        total += this.boxList[i].count
      }
      this.header.count = total
      this.header.prdCount = this.header.count
    }
  }
}
</script>

<style lang="scss" scoped>
.body {
  padding: 20px 0;
  .header {
    margin-top: 20px;
    position: relative;
    .header_row {
      display: flex;
      >div {
        flex-shrink: 0;
      }
      :deep(.produceDate) {
        .el-input {
          width: 100%!important;
        }
      }
    }
    .audit_icon {
      position: absolute;
      top: -10px;
      left: 60px;
      font-size: 48px;
      color: red;
    }
    .material {
      width: 100%;
    }
    .p3 {
      :deep(.el-form-item__content) {
        display: flex;
        .comment {
          margin-left: 10px;
          word-break: keep-all;
        }
      }
    }
  }
  .detail_header {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    .stat {
      display: flex;
      font-size: 15px;
      >div {
        display: flex;
        align-items: baseline;
        line-height: 32px;
        .label {
          text-align: right;
          margin-right: 5px;
          color: #aaa;
        }
        .value {
          min-width: 50px;
          margin-right: 10px;
          color: #666;
        }
      }
    }
  }
}
:deep(.el-form-item__label) {
  width: 82px !important;
}
</style>
